<?php
/**
 * 智力挑战模块微站定义
 *
 * @author junsion
 * @url http://s.we7.cc/index.php?c=store&a=author&uid=74516
 */
defined('IN_IA') or exit('Access Denied');
require_once IA_ROOT.'/addons/junsion_challeng/func.php';
class Junsion_challengModuleSite extends WeModuleSite {

	public function doWebRedis(){
		global $_W,$_GPC;
		if ($_GPC['op']){
			$r = new Redis();
			$r->connect(trim($_GPC['rip']), trim($_GPC['rport']));
			if (trim($_GPC['rpasswd']) && $r->auth(trim($_GPC['rpasswd'])) == false) {
				die('-1');
			}
			if ($r->ping() != '+PONG') die('-1');
			die('1');
		}
		if (!extension_loaded('redis')) {
			die('-1');
		}
		die();
	}
	
	public function doWebFooter(){
		global $_W,$_GPC;
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		if('post' == $op){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_footer')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				$title = trim($_GPC['title']);//菜单名称
				if (empty($title)) {
					message('菜单名称不能为空!');
				}
	
				$data = array(
						'weid'=>$_W['uniacid'],
						'title'=>$title,
						'color'=>$_GPC['color'],
						'thumb'=>$_GPC['thumb'],
						'url'=>$_GPC['url'],
						'displayorder'=>$_GPC['displayorder'],
				);
				if(empty($id)){
					pdo_insert($this->modulename.'_footer', $data);//添加数据
					message('菜单添加成功！', $this->createWebUrl('footer', array('op' => 'display')), 'success');
				}else{
					$t = "'{$title}'";
					if ($title != $item['title']){
						$t = "修改菜单名'".$item['title']."'为'".$title."'";
					}
					pdo_update($this->modulename.'_footer', $data, array('id' => $id));
					message('菜单更新成功！', $this->createWebUrl('footer', array('op' => 'display')), 'success');
				}
			}
		}else if('del' == $op){//删除数据
			//权限限制
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id,title FROM ".tablename($this->modulename.'_footer')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('菜单不存在！');
			}
			pdo_delete($this->modulename.'_footer', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}else if('display'==$op){
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_footer')." WHERE weid = '{$_W['weid']}' order by displayorder desc");//分页
		}
		include $this->template('footer');
	}
	
	public function doWebImport(){
		global $_W,$_GPC;
		set_time_limit(0);
		ini_set('memory_limit', '2G');
		include_once '../addons/junsion_challeng/excel/oleread.php';
		include_once '../addons/junsion_challeng/excel/excel.php';
		if ( !empty( $_FILES ['txtfile']['name'] )) {
			$tmp_name  =  $_FILES [ "txtfile" ][ "tmp_name" ];
			$name = $_FILES [ "txtfile" ][ "name" ];
			$filename  =  ATTACHMENT_ROOT.date ( 'Ymdhis' ).'.'.pathinfo($name,PATHINFO_EXTENSION);
			if (move_uploaded_file ( $tmp_name , $filename )) {
				$xls = new Spreadsheet_Excel_Reader ();
				$xls->setOutputEncoding ( 'utf-8' ); // 设置编码
				$xls->read ( $filename ); // 解析文件
				for($i = 2; $i <= $xls->sheets [0] ['numRows']; $i ++) {
					$data_values [] = $xls->sheets [0] ['cells'] [$i];
				}
			}
			$op = $_GPC['op'];
			$insert_val = "";
			$count = 0;
			if($op == 'phrase'){
				$inert_sql = "INSERT INTO ".tablename('junsion_challeng_phrase')." (phrase) ";
				foreach($data_values as $value){
					if($value[1] == '') break;
					if(!empty($insert_val)){
						$insert_val .= ", ";
					}
					$insert_val .= " ( '{$value[1]}' ) ";
					$count++;
				}
			}
			elseif($op == 'pic'){
				$inert_sql = "INSERT INTO ".tablename('junsion_challeng_pic')." (weid,thumb,answer,status) ";
				foreach($data_values as $value){
					if($value[1] == '') break;
					if($value[3] == '') $status = 1;
					else $status = $value[3];
					if(!empty($insert_val)){
						$insert_val .= ", ";
					}
					$insert_val .= " ( '{$_W['uniacid']}','{$value[1]}','{$value[2]}','{$status}' ) ";
					$count++;
				}
			}
			else{
				$inert_sql = "INSERT INTO ".tablename('junsion_challeng_problem')." (weid,title,answers,answer,level,status) ";
				foreach($data_values as $value){
					if($value[1] == '') break;
					$answers_app = $value[2];
					$answers_app = str_replace('；', ';', $answers_app);
					$answers_app = explode(';', $answers_app);
					$answers = array();
					foreach ($answers_app as $ka => $v){
						$answers[$ka]['answers'] = $v;
					}
					$answers = serialize($answers);
				
					if($value[4] == '') $level = 0;
					else $level = $value[4];
					if($value[5] == '') $status = 1;
					else $status = $value[5];
				
					if(!empty($insert_val)){
						$insert_val .= ", ";
					}
					$insert_val .= " ( '{$_W['uniacid']}','{$value[1]}','{$answers}','{$value[3]}','{$level}','{$status}' ) ";
					$count++;
				}
			}
			if(!empty($insert_val)){
				$inert_sql .= " VALUES ".$insert_val;
				$ret = pdo_query($inert_sql);
				if($ret > 0){
					message('导入记录 '.$count.' 条',referer());
				}else{
					message('导入错误，请刷新重试！');
				}
			}else{
				message('抱歉！导入信息有误，请重试',referer(),'error');
			}
		}else message('没有导入模板');
	}
	
	public function doWebProblem(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['kwd'])){
				$condition .= " and  title like '%{$_GPC['kwd']}%'";
			}
			if($_GPC['status']!=''){
				$condition .= " and status = '{$_GPC['status']}' ";
			}
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_problem') . " where weid = '{$weid}' {$condition} order by id desc {$limit}");
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_problem') . " where weid = '{$weid}' {$condition} ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif($op == 'post'){
			$id = $_GPC['id'];
			if(!empty($id)){
				$item = pdo_fetch('select * from ' . tablename($this->modulename.'_problem') . " where id = '{$id}'" );
				$answers = unserialize($item['answers']);
			}
			if(checksubmit()){
				$answer = array();
				$answers_num = $_GPC['answers'];
				if(!empty($answers_num)){
					foreach ($answers_num as $k => $v){
						if(!empty($v)){
							$answer[] = array(
									'answers' => $v,
							);
						}
					}
				}
				$data = array(
						'weid' => $weid,
						'title' => trim($_GPC['title']),
						'answer' => intval($_GPC['answer']),
						'answers' => serialize($answer),
						'level' => intval($_GPC['level']),
						'status' => intval($_GPC['status']),
				);
				if ($item){
					pdo_update($this->modulename.'_problem',$data,array('id'=>$id));
					message('操作成功',$this->createWebUrl('problem'),'success');
				}else{
					pdo_insert($this->modulename.'_problem',$data);
					message('操作成功',$this->createWebUrl('problem'),'success');
				}
			}
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select id from ' . tablename($this->modulename.'_problem') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('problem'),'error');
			}
			if(pdo_delete($this->modulename.'_problem',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功','referer','success');
		}
		elseif ($op == 'delall') {
			pdo_query('delete from '. tablename($this->modulename.'_problem') . " where weid = '{$weid}' ");
			message('操作成功','referer','success');
		}
		elseif($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_problem")." set status = !status where id='{$id}'");
			die('1');
		}
		include $this->template('problem');
	}
	
	public function doWebPic(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		$pic_url = $this->module['config']['game5']['iurl'];
		if(empty($pic_url)) $pic_url = $_W['siteroot'].'addons/junsion_challeng/public/pics/';
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['kwd'])){
				$condition .= " and  answer like '%{$_GPC['kwd']}%'";
			}
			if($_GPC['status']!=''){
				$condition .= " and status = '{$_GPC['status']}' ";
			}
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_pic') . " where weid = '{$weid}' {$condition} order by id desc {$limit}");
			if(!empty($list)){
				foreach ($list as $k => &$v){
					$v['thumb'] = $pic_url.$v['thumb'];
				}
				unset($v);
			}
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_pic') . " where weid = '{$weid}' {$condition} ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif($op == 'post'){
			$id = $_GPC['id'];
			if(!empty($id)){
				$item = pdo_fetch('select * from ' . tablename($this->modulename.'_pic') . " where id = '{$id}'" );
				$item['thumb'] = $pic_url.$item['thumb'];
			}
			if(checksubmit()){
				$data = array(
						'weid' => $weid,
						'thumb' => trim($_GPC['thumb']),
						'answer' => trim($_GPC['answer']),
						'status' => intval($_GPC['status']),
				);
				if ($item){
					pdo_update($this->modulename.'_pic',$data,array('id'=>$id));
					message('操作成功',$this->createWebUrl('pic'),'success');
				}else{
					pdo_insert($this->modulename.'_pic',$data);
					message('操作成功',$this->createWebUrl('pic'),'success');
				}
			}
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select id from ' . tablename($this->modulename.'_pic') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('pic'),'error');
			}
			if(pdo_delete($this->modulename.'_pic',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功','referer','success');
		}
		elseif ($op == 'delall') {
			pdo_query('delete from '. tablename($this->modulename.'_pic') . " where weid = '{$weid}' ");
			message('操作成功','referer','success');
		}
		elseif($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_pic")." set status = !status where id='{$id}'");
			die('1');
		}
		include $this->template('pic');
	}
	
	public function doWebPhrase(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['kwd'])){
				$condition .= " and  phrase like '%{$_GPC['kwd']}%'";
			}
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_phrase') . " where 1 {$condition} order by id desc {$limit}");
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_phrase') . " where 1 {$condition} ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif($op == 'post'){
			$id = $_GPC['id'];
			if(!empty($id)){
				$item = pdo_fetch('select * from ' . tablename($this->modulename.'_phrase') . " where id = '{$id}'" );
			}
			if(checksubmit()){
				$data = array(
						'phrase' => trim($_GPC['phrase']),
				);
				if ($item){
					pdo_update($this->modulename.'_phrase',$data,array('id'=>$id));
					message('操作成功',$this->createWebUrl('phrase'),'success');
				}else{
					pdo_insert($this->modulename.'_phrase',$data);
					message('操作成功',$this->createWebUrl('phrase'),'success');
				}
			}
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select id from ' . tablename($this->modulename.'_phrase') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('phrase'),'error');
			}
			if(pdo_delete($this->modulename.'_phrase',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功','referer','success');
		}
		elseif ($op == 'delall') {
			pdo_query('delete from '. tablename($this->modulename.'_phrase') . " where 1 ");
			message('操作成功','referer','success');
		}
		include $this->template('phrase');
	
	}
	
	public function doWebOrder(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		$t = time();
		$t = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
		pdo_query('delete from '. tablename($this->modulename.'_order') . " where status = 0 and createtime < '{$t}' ");
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['m_kwd'])){
				$condition .= " and ( mid in (select id from ".tablename($this->modulename."_mem")." where nickname like '%{$_GPC['m_kwd']}%' and weid='{$_W['uniacid']}' ) )";
			}
			if($_GPC['status']!=''){
				$condition .= " and status = '{$_GPC['status']}' ";
			}
			if($_GPC['paytype']!=''){
				$condition .= " and paytype = '{$_GPC['paytype']}' ";
			}
			$start = $_GPC['dateline']?strtotime($_GPC['dateline']['start']):(time()-30*24*3600);
			$end = $_GPC['dateline']?strtotime($_GPC['dateline']['end']):time();
			$condition .= " and createtime >= '{$start}' and  createtime <= '{$end}'";
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_order') . " where weid = '{$weid}' {$condition} order by id desc {$limit}");
			if(!empty($list)){
				foreach ($list as $k => $v){
					$mids[] = $v['mid'];
					$gids[] = $v['gid'];
				}
				$mids = array_unique($mids);
				$mems = pdo_fetchall('select id,nickname,avatar from ' . tablename($this->modulename.'_mem') . " where weid = '{$weid}' and id in ( " . implode(',', $mids) . " )",array(),'id');
				unset($v);
			}
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_order') . " where weid = '{$weid}' {$condition} ");
			$money = pdo_fetchcolumn('select sum(price) from ' . tablename($this->modulename.'_order') . " where weid = '{$weid}' {$condition} ");
			$total1 = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_order') . " where weid = '{$weid}' ");
			$money1 = pdo_fetchcolumn('select sum(price) from ' . tablename($this->modulename.'_order') . " where weid = '{$weid}' ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select * from ' . tablename($this->modulename.'_order') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('order'),'error');
			}
			if(pdo_delete($this->modulename.'_order',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功','referer','success');
		}
		include $this->template('order');
	}
	
	public function doWebReward(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		$times = time();
		$todaystart = mktime(0,0,0,date("m",$times),date("d",$times),date("Y",$times));
		pdo_query('delete from '. tablename($this->modulename.'_nums') . " where createtime < '{$todaystart}' and type!=2");
		$allgifts = getall('select id,title,logo,price from ' . tb('gift') . " where status = 1");
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['m_kwd'])){
				$condition .= " and ( mid in (select id from ".tablename($this->modulename."_mem")." where nickname like '%{$_GPC['m_kwd']}%' and weid='{$_W['uniacid']}' ) )";
			}
			if(!empty($_GPC['g_kwd'])){
				$condition .= " and ( gid in (select id from ".tablename($this->modulename."_gift")." where ( title like '%{$_GPC['g_kwd']}%' ) and weid='{$_W['uniacid']}' ) )";
			}
			if($_GPC['status']!=''){
				$condition .= " and status = '{$_GPC['status']}' ";
			}
			if($_GPC['gtype']!=''){
				$condition .= " and type = '{$_GPC['gtype']}' ";
			}
			if($_GPC['paytype']!=''){
				$condition .= " and paytype = '{$_GPC['paytype']}' ";
			}
			$start = $_GPC['dateline']?strtotime($_GPC['dateline']['start']):(time()-30*24*3600);
			$end = $_GPC['dateline']?strtotime($_GPC['dateline']['end']):time();
			$condition .= " and createtime >= '{$start}' and  createtime <= '{$end}'";
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_reward') . " where weid = '{$weid}' {$condition} order by id desc {$limit}");
			if(!empty($list)){
				foreach ($list as $k => $v){
					$mids[] = $v['mid'];
					$gids[] = $v['gid'];
				}
				$mids = array_unique($mids);
				$mems = pdo_fetchall('select id,nickname,avatar from ' . tablename($this->modulename.'_mem') . " where weid = '{$weid}' and id in ( " . implode(',', $mids) . " )",array(),'id');
				$gids = array_unique($gids);
				$gifts = pdo_fetchall('select id,title,logo from ' . tablename($this->modulename.'_gift') . " where weid = '{$weid}' and id in ( " . implode(',', $gids) . " )",array(),'id');
				unset($v);
			}
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_reward') . " where weid = '{$weid}' {$condition} ");
			$money = pdo_fetchcolumn('select sum(price) from ' . tablename($this->modulename.'_reward') . " where weid = '{$weid}' {$condition} ");
			$total1 = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_reward') . " where weid = '{$weid}' ");
			$money1 = pdo_fetchcolumn('select sum(price) from ' . tablename($this->modulename.'_reward') . " where weid = '{$weid}' ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select * from ' . tablename($this->modulename.'_reward') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('reward'),'error');
			}
			$gift = get('select id,price from ' . tb('gift') . " where weid='{$_W['uniacid']}' and id='{$item['gid']}' ");
			pdo_query('update '.tablename($this->modulename."_mem")." set reward_num = reward_num-1,reward_price=reward_price-'{$gift['price']}' where id='{$item['mid']}'");
			if(pdo_delete($this->modulename.'_reward',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功','referer','success');
		}
		elseif ($op == 'send') {
			$id = $_GPC['id'];
			$gid = $_GPC['gid'];
			$item = pdo_fetch('select id,mid from ' . tablename($this->modulename.'_reward') . " where id = '{$id}'");
			$ret = pdo_update($this->modulename.'_reward',array('status'=>2,'gid'=>$gid),array('id'=>$id));
			die('1');
		}
		include $this->template('reward');
	}
	
	public function doWebGames(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['keyword'])){
				$condition .= " and title like '%{$_GPC['keyword']}%' ";
			}
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_games') . " where weid = '{$weid}' {$condition} order by sort desc {$limit}");
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_games') . " where weid = '{$weid}' ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif($op == 'post'){
			$id = $_GPC['id'];
			if(!empty($id)){
				$item = pdo_fetch('select * from ' . tablename($this->modulename.'_games') . " where id = '{$id}'" );
			}
			if(checksubmit()){
				$data = array(
						'weid' => $weid,
						'title' => trim($_GPC['title']),
						'thumb' => trim($_GPC['thumb']),
						'des' => trim($_GPC['des']),
						'url' => trim($_GPC['url']),
						'appid' => trim($_GPC['appid']),
						'dummy_num' => intval($_GPC['dummy_num']),
						'sort' => intval($_GPC['sort']),
						'status' => intval($_GPC['status']),
				);
				if ($item){
					pdo_update($this->modulename.'_games',$data,array('id'=>$id));
					message('操作成功',$this->createWebUrl('games'),'success');
				}else{
					pdo_insert($this->modulename.'_games',$data);
					message('操作成功',$this->createWebUrl('games'),'success');
				}
			}
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select * from ' . tablename($this->modulename.'_games') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('games'),'error');
			}
			if(pdo_delete($this->modulename.'_games',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功',$this->createWebUrl('games'),'success');
		}
		elseif($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_games")." set status = !status where id='{$id}'");
			die('1');
		}
		include $this->template('games');
	}
	
	public function doWebGift(){
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['keyword'])){
				$condition .= " and title like '%{$_GPC['keyword']}%' ";
			}
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_gift') . " where weid = '{$weid}' {$condition} order by sort desc {$limit}");
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_gift') . " where weid = '{$weid}' ");
			$pager = pagination($total, $pindex, $psize);
		}
		elseif($op == 'post'){
			$id = $_GPC['id'];
			if(!empty($id)){
				$item = pdo_fetch('select * from ' . tablename($this->modulename.'_gift') . " where id = '{$id}'" );
			}
			if(checksubmit()){
				$data = array(
						'weid' => $weid,
						'title' => trim($_GPC['title']),
						'logo' => trim($_GPC['logo']),
						'price' => trim($_GPC['price']),
						'sort' => intval($_GPC['sort']),
						'status' => intval($_GPC['status']),
						'isdefault' => intval($_GPC['isdefault']),
				);
				if($data['isdefault']==1){
					pdo_query('update '.tablename($this->modulename."_gift")." set isdefault = 0 where 1");
				}
				if ($item){
					pdo_update($this->modulename.'_gift',$data,array('id'=>$id));
					message('操作成功',$this->createWebUrl('gift'),'success');
				}else{
					pdo_insert($this->modulename.'_gift',$data);
					message('操作成功',$this->createWebUrl('gift'),'success');
				}
			}
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select * from ' . tablename($this->modulename.'_gift') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('gift'),'error');
			}
			if(pdo_delete($this->modulename.'_gift',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功',$this->createWebUrl('gift'),'success');
		}
		elseif($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_gift")." set status = !status where id='{$id}'");
			die('1');
		}
		include $this->template('gift');
	}
	
	public function wisepayPay($params,$type='weixin'){
		global $_W,$_GPC;
		$money = $params['money'];
		$orderno = $params['orderno'];
		$appid = $_W['account']['key'];//小程序appid
		$openid = $params['openid'];
	
		$cfg = $this->module['config'];
		$ps = $cfg['wisepay'];
		$key = $ps['appkey'];
		$url = "http://pay.congmingpay.com/pay/miniapppay.do?";
		$str = "money={$money}&orderId={$orderno}&shopId={$ps['shopid']}";
		$sign = strtoupper(md5($str.'&key='.$key));
		$url .= $str."&sign={$sign}";
		$url .= '&type='.$type;
		$url .= '&appid='.$appid;
		$url .= '&appOpenid='.$openid;
		$url .= "&redirectUrl={$_W['siteroot']}addons/junsion_challeng/wisepay/return.php";
		load()->func('communication');
		$result = ihttp_get($url);
		$result = json_decode($result['content'],true);
		if(!empty($result)) return $result;
		return 0;
	}
	

	public function ch2arr($str)
	{
		$length = mb_strlen($str, 'utf-8');
		$array = [];
		for ($i=0; $i<$length; $i++)
			$array[] = mb_substr($str, $i, 1, 'utf-8');
			return $array;
	}
	
	public function doWebTrans(){
		global $_W,$_GPC;
		$uniacid = intval($_GPC['acc_id']);
		if (empty($uniacid)) MSG('请选择目标小程序');
	
		del('mem',array('weid'=>$uniacid));
		del('gift',array('weid'=>$uniacid));
		del('problem',array('weid'=>$uniacid));
		del('reward',array('weid'=>$uniacid));
		del('order',array('weid'=>$uniacid));
		del('footer',array('weid'=>$uniacid));
		del('games',array('weid'=>$uniacid));
		del('friends',array('weid'=>$uniacid));
	
		update('mem',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('gift',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('problem',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('reward',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('order',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('footer',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('games',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
		update('friends',array('weid'=>$uniacid),array('weid'=>$_W['uniacid']));
	
		pdo_delete('uni_account_modules',array('uniacid'=>$uniacid));
		pdo_update('uni_account_modules',array('uniacid'=>$uniacid),array('uniacid'=>$_W['uniacid']));
	
		pdo_update('rule',array('name'=>'junsion_challeng'.$uniacid),array('name'=>'junsion_challeng'.$_W['uniacid']));
		pdo_update('rule_keyword',array('content'=>'junsion_challeng'.$uniacid),array('content'=>'junsion_challeng'.$_W['uniacid']));
		file_put_contents(IA_ROOT."/addons/junsion_challeng/preuniacid{$uniacid}", $_W['uniacid']);
		message ( '转移成功，请更新缓存后查看目标小程序数据', $this->createWebUrl('mem'));
	}
	
	public function doWebMem() {
		//这个操作被定义用来呈现 管理中心导航菜单
		global $_W,$_GPC;
		$op = empty($_GPC['op'])?'display':$_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(intval($_GPC['page']), 1);
			$psize = 20;
			$condition = "";
			if(!empty($_GPC['keyword'])){
				$condition .= " and nickname like '%{$_GPC['keyword']}%' ";
			}
			if($_GPC['status']!=''){
				$condition .= " and status = '{$_GPC['status']}' ";
			}
			$limit = "limit " . (($pindex -1) * $psize).','. $psize;
			$list = pdo_fetchall('select * from ' . tablename($this->modulename.'_mem') . " where weid = '{$weid}' {$condition} order by id desc {$limit}");
			$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_mem') . " where weid = '{$weid}' ");
			$pager = pagination($total, $pindex, $psize);
			
			$accounts = getall("select w.uniacid,w.name from ".tablename('account_wxapp')." w left join ".tablename('account')." a on w.uniacid=a.uniacid where w.uniacid != '{$_W['uniacid']}' and a.isdeleted=0",'uniacid');
			if ($accounts){
				$uids = array_keys($accounts);
				$uids = array_unique($uids);
				$us = getall("select uniacid from ".tablename('uni_account_modules')." where uniacid in (".implode(',', $uids).") and module!='junsion_challeng'");
				foreach ($us as $value) {
					unset($accounts[$value['uniacid']]);
				}
			}
		}
		elseif ($op == 'del') {
			$id = $_GPC['id'];
			$item = pdo_fetch('select * from ' . tablename($this->modulename.'_mem') . " where id = '{$id}'");
			if(empty($item)){
				message('操作失败',$this->createWebUrl('mem'),'error');
			}
			pdo_delete($this->modulename.'_collect',array('mid'=>$id));
			pdo_delete($this->modulename.'_collect_act',array('mid'=>$id));
			if(pdo_delete($this->modulename.'_mem',array('id'=>$id)) === false) message('操作失败',referer(),'error');
			else message('操作成功',$this->createWebUrl('mem'),'success');
		}
		elseif($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_mem")." set status = !status where id='{$id}'");
			die('1');
		}
		include $this->template('mem');
	}

	public function payResult($params){
		global $_W, $_GPC;
		file_put_contents(IA_ROOT."/addons/junsion_challeng/pay", date('Y-m-d H:i:s')."： params:".json_encode($params)."\n",FILE_APPEND);
		$table = $params['table'];
		if($table=='order'){
			$order = pdo_fetch('select * from ' . tablename($this->modulename.'_order') . " where orderno = '{$params['tid']}'");
			if(empty($order) || $order['status'] > 0){
				return "";
			}
			if ($params['from'] == 'notify') {
				if($params['type']=='yun'){
					$res = array();
					$res['code']=1;
					$res['fee'] = $order['price'];
				}else{
					$res = $this->checkWechatTran($_W['uniacid'], $params['tag']['transaction_id']);
				}
				file_put_contents(IA_ROOT."/addons/junsion_challeng/pay", date('Y-m-d H:i:s')." res:".json_encode($res)." order:".json_encode($order)."\n",FILE_APPEND);
				if ($res['code']==1 && $res['fee'] == $order['price']){
					$update_data = array(
							'status' => 1,
							'transid' => $params['tag']['transaction_id'],
					);
					pdo_update($this->modulename."_order",$update_data,array('id'=>$order['id']));
					pdo_query('update '.tablename($this->modulename."_mem")." set challeng_num = challeng_num+'{$order['num']}' where id='{$order['mid']}'");
				}
			}
			if ($params['from'] == 'return'){
				echo '支付成功';
				exit;
			}
		}
		else{
			$order = pdo_fetch('select * from ' . tablename($this->modulename.'_reward') . " where orderno = '{$params['tid']}'");
			if(empty($order) || $order['status'] > 0){
				return "";
			}
			if ($params['from'] == 'notify') {
				if($params['type']=='yun'){
					$res = array();
					$res['code']==1;
					$res['fee'] = $order['price'];
				}else{
					$res = $this->checkWechatTran($_W['uniacid'], $params['tag']['transaction_id']);
				}
				file_put_contents(IA_ROOT."/addons/junsion_challeng/pay", date('Y-m-d H:i:s')." res:".json_encode($res)." order:".json_encode($order)."\n",FILE_APPEND);
				if ($res['code']==1 && $res['fee'] == $order['price']){
					$update_data = array(
							'status' => 1,
							'transid' => $params['tag']['transaction_id'],
					);
					pdo_update($this->modulename."_reward",$update_data,array('id'=>$order['id']));
				}
			}
			if ($params['from'] == 'return'){
				echo '支付成功';
				exit;
			}
		}
	}
	
	public function doMobilePayReward(){
		global $_W,$_GPC;
		$weid = $_W['uniacid'];
		$id = $_GPC['id'];
		$reward = pdo_fetch('select id,status from ' . tablename($this->modulename.'_reward') . " where id = '{$id}' and weid='{$_W['uniacid']}'");
		if(empty($reward)){
			$arr = array(
					'code' => 0,
					'msg' => '中奖记录不存在'
			);
			die(json_encode($arr));
		}
		if($reward['status']!=0){
			$arr = array(
					'code' => 0,
					'msg' => '该奖品已被领取'
			);
			die(json_encode($arr));
		}
		$openid = $_GPC['openid'];
		if(empty($openid)){
			$arr = array(
					'code' => 0,
					'msg' => '获取粉丝信息失败'
			);
			die(json_encode($arr));
		}
		$mem = pdo_fetch('select id,status from ' . tablename($this->modulename.'_mem') . " where propenid = '{$openid}' and weid='{$_W['uniacid']}'");
		if($mem['status']==1){
			$arr = array(
					'code' => 0,
					'msg' => '您已被拉入黑名单，无法获取奖品'
			);
			die(json_encode($arr));
		}
		$paytype = $_GPC['paytype'];
		if($paytype>1 || $paytype<0){
			$arr = array(
					'code' => 0,
					'msg' => '支付方式不存在，请重新选择'
			);
			die(json_encode($arr));
		}
		$uname = $_GPC['uname'];
		if(empty($uname)){
			$arr = array(
					'code' => 0,
					'msg' => '请输入联系人姓名'
			);
			die(json_encode($arr));
		}
		$mobile = $_GPC['mobile'];
		if(empty($mobile)){
			$arr = array(
					'code' => 0,
					'msg' => '请输入联系方式'
			);
			die(json_encode($arr));
		}
		$remark = $_GPC['remark'];
		$addr = $_GPC['addr'];
		if(empty($addr)){
			$arr = array(
					'code' => 0,
					'msg' => '请输入地址'
			);
			die(json_encode($arr));
		}
		
		$cfg = $this->module['config'];
		$wisepay = $cfg['wisepay'];
		$price = $cfg['base']['express_fee'];
		$ordersn = "J".date('YmdHis',time()).random(10,1);
		$update_data = array(
				'orderno' => $ordersn,
				'price' => $price,
				'mid' => $mem['id'],
				'paytype' => $paytype,
				'uname' => $uname,
				'mobile' => $mobile,
				'addr' => $addr,
				'remark' => $remark,
		);
		if($price<=0){
			$update_data['status']=1;
			$ret = pdo_update($this->modulename.'_reward',$update_data,array('id'=>$id));
			if($ret){
				$arr = array(
						'code' => 10,
						'msg' => '完善信息成功'
				);
			}
			else{
				$arr = array(
						'code' => 0,
						'msg' => '完善信息失败，请稍后重试'
				);
			}
			die(json_encode($arr));
		}
		else{
			$ret = pdo_update($this->modulename.'_reward',$update_data,array('id'=>$id));
			if($ret){
				if($wisepay['status']==1){
					//聪明付
					$pay_data = array(
							'money' => $data['price'],
							'orderno' => $data['orderno'],
							'openid' => $openid
					);
					$res = $this->wisepayPay($pay_data);
					if(!empty($res)){
						$result = array(
								"errcode"=>0,
								"appId"=>$_W['uniaccount']['key'],
								"timeStamp"=>$res['timeStamp'],
								"nonceStr"=>$res['nonceStr'],
								'package'=>$res['prepay_id'],
								"signType"=>'MD5',
								"paySign"=>$res['paySign'],
								"orderid"=>$newid,
						);
						$arr = array(
								'code' => 1,
								'res' => $result
						);
					}
					else{
						$arr = array(
								'code' => 0,
								'msg' => '调起支付失败，请联系管理员'
						);
					}
					die(json_encode($arr));
				}
				else{
					$preresult = $this->unifiedOrder($openid,'奖品邮费',$price,$ordersn,'reward');
					$result = array();
					if($preresult['errcode'] == 0){
						$params = $this->getWxPayJsParams($preresult['prepay_id']);
						$result = array(
								"errcode"=>0,
								"appId"=>$_W['uniaccount']['key'],
								"timeStamp"=>$params['timeStamp'],
								"nonceStr"=>$params['nonceStr'],
								"package"=>$params['package'],
								"signType"=>$params['signType'],
								"paySign"=>$params['paySign'],
								"orderid"=>$id,
						);
						$arr = array(
								'code' => 1,
								'res' => $result
						);
					}else{
						$arr = array(
								'code' => 0,
								'res' => $preresult['errmsg']
						);
					}
					die(json_encode($arr));
				}
			}
			else{
				$arr = array(
						'code' => 0,
						'msg' => '完善信息失败，请稍后重试'
				);
				die(json_encode($arr));
			}
		}
	}
	
	public function doMobileCreateOrder(){
		global $_W,$_GPC;
		$weid = $_W['uniacid'];
		$openid = $_GPC['openid'];
		if(empty($openid)){
			$arr = array(
					'code' => 0,
					'msg' => '获取粉丝信息失败'
			);
			die(json_encode($arr));
		}
		$selkey = $_GPC['selkey'];
		$paytype = $_GPC['paytype'];
		if($paytype>1 || $paytype<0){
			$arr = array(
					'code' => 0,
					'msg' => '支付方式不存在，请重新选择'
			);
			die(json_encode($arr));
		}
		$cfg = $this->module['config'];
		$wisepay = $cfg['wisepay'];
		$price = $cfg['price'];
		if(empty($price[$selkey])){
			$arr = array(
					'code' => 0,
					'msg' => '购买次数有误，请重新选择'
			);
			die(json_encode($arr));
		}
		$mem = pdo_fetch('select id from ' . tablename($this->modulename.'_mem') . " where propenid = '{$openid}' and weid='{$_W['uniacid']}'");
		$ordersn = "J".date('YmdHis',time()).random(10,1);
		$data = array(
				'weid' => $_W['uniacid'],
				'orderno' => $ordersn,
				'price' => $price[$selkey]['price'],
				'num' => $price[$selkey]['num'],
				'mid' => $mem['id'],
				'paytype' => $paytype,
				'createtime' => TIMESTAMP
		);
		pdo_insert($this->modulename.'_order',$data);
		$newid = pdo_insertid();
		if($newid>0){
			if($wisepay['status']==1){
				//聪明付
				$pay_data = array(
						'money' => $data['price'],
						'orderno' => $data['orderno'],
						'openid' => $openid
				);
				$res = $this->wisepayPay($pay_data);
				if(!empty($res)){
					$result = array(
							"errcode"=>0,
							"appId"=>$_W['uniaccount']['key'],
							"timeStamp"=>$res['timeStamp'],
							"nonceStr"=>$res['nonceStr'],
							'package'=>$res['prepay_id'],
							"signType"=>'MD5',
							"paySign"=>$res['paySign'],
							"orderid"=>$newid,
					);
					$arr = array(
							'code' => 1,
							'res' => $result
					);
				}
				else{
					$arr = array(
							'code' => 0,
							'msg' => '调起支付失败，请联系管理员'
					);
				}
				die(json_encode($arr));
			}
			else{
				$preresult = $this->unifiedOrder($openid,'购买挑战次数费用',$data['price'],$ordersn,'order');
				$result = array();
				if($preresult['errcode'] == 0){
					$params = $this->getWxPayJsParams($preresult['prepay_id']);
					$result = array(
							"errcode"=>0,
							"appId"=>$_W['uniaccount']['key'],
							"timeStamp"=>$params['timeStamp'],
							"nonceStr"=>$params['nonceStr'],
							"package"=>$params['package'],
							"signType"=>$params['signType'],
							"paySign"=>$params['paySign'],
							"orderid"=>$newid,
					);
					$arr = array(
							'code' => 1,
							'res' => $result
					);
				}else{
					$arr = array(
							'code' => 0,
							'msg' => $preresult['errmsg']
					);
				}
				die(json_encode($arr));
			}
		}
		else{
			$arr = array(
					'code' => 0,
					'msg' => '创建订单失败，请稍后重试'
			);
			die(json_encode($arr));
		}
	}
	
	public function unifiedOrder($openid,$remark,$fee,$orderid=0,$table=''){
		global $_W;
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		$random = random(8);
		$cfg = $this->module['config'];
		$post = array(
				'appid'=>$_W['uniaccount']['key'],
				'mch_id'=>$cfg['mchid'],
				'nonce_str'=>$random,
				'body'=>$remark,
				'out_trade_no'=>$orderid,
				'total_fee'=>$fee*100,
				'spbill_create_ip'=>CLIENT_IP,
				'notify_url'=>$_W['siteroot'].'/addons/'.$this->modulename.'/notify.php',
				'trade_type'=>'JSAPI',
				'openid'=>$openid,
				'attach'=>$_W['uniacid'].':'.$table,
				'limit_pay'=>'no_credit',
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$cfg['APPKEY']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$resp = $this->postXmlCurl($this->ToXml($post), $url);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		if ($resp['result_code'] != 'SUCCESS') {
			return array('errcode'=>1,'errmsg'=>json_encode($resp));
		}else{
			return array('errcode'=>0,'prepay_id'=>$resp['prepay_id'],'code_url'=>$resp['code_url']);
		}
	}
	private function checkWechatTran($uniacid,$transid){
		$appid = pdo_fetchcolumn('select `key` from ' . tablename('account_wxapp') . " where uniacid = '{$uniacid}'");
		$cfg = $this->module['config'];
		$url = "https://api.mch.weixin.qq.com/pay/orderquery";
		$random = random(8);
		$post = array(
				'appid'=>$appid,
				'transaction_id'=>$transid,
				'nonce_str'=>$random,
				'mch_id'=>$cfg['mchid'],
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$cfg['APPKEY']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$resp = $this->postXmlCurl($this->ToXml($post), $url);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		if ($resp['result_code'] != 'SUCCESS' || $resp['return_code'] != 'SUCCESS') {
			exit('fail');
		}
		if ($resp['trade_state'] == 'SUCCESS') return array('code'=>1,'fee'=>$resp['total_fee']/100);
	}
	
	/**
	 * 支付js pai 参数
	 * @param unknown $prepay_id
	 * @return multitype:string NULL unknown
	 */
	private function getWxPayJsParams($prepay_id){
		global $_W;
		$cfg = $this->module['config'];
		$random = random(8);
		$post = array(
				'appId'=>$_W['uniaccount']['key'],
				'timeStamp'=>time().'',
				'nonceStr'=>$random,
				'package'=>"prepay_id=".$prepay_id,
				'signType'=>'MD5',
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$cfg['APPKEY']}";
		$sign = md5($string);
		$post['paySign'] = strtoupper($sign);
		return $post;
	}
	private function ToUrlParams($post)
	{
		$buff = "";
		foreach ($post as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	private function ToXml($post)
	{
		$xml = "<xml>";
		foreach ($post as $key=>$val)
		{
			if (is_numeric($val)){
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		return $xml;
	}
	
	private function postXmlCurl($xml, $url, $useCert = false, $second = 30){
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
	
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);//严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	
		if($useCert == true){
			//设置证书
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
		}
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		}
	}
	public function doMobileCheckOrder(){
		global $_GPC, $_W;
		$orderid = $_GPC['orderid'];
		echo pdo_fetchcolumn('select status from '.tablename($this->modulename."_order")." where id='{$orderid}'");
	}
	public function doMobileCheckReward(){
		global $_GPC, $_W;
		$orderid = $_GPC['orderid'];
		echo pdo_fetchcolumn('select status from '.tablename($this->modulename."_reward")." where id='{$orderid}'");
	}
	
	public function getGuide($wechat,$mem,$type = 0){
		foreach ($wechat as $k => $v){
			$f = pdo_fetch("select follow from ".tablename('mc_mapping_fans')." where unionid='{$mem['unionid']}' and uniacid='{$v['wechat']}'");
			if (!empty($f['follow'])) continue;
			return $type?$v['wechat']:$v['link'];
		}
		return '';
	}
	
	public function doMobileUrl(){
		global $_W,$_GPC;
		$mid = intval($_GPC['mid']);
		$token = $_GPC['token'];
		$cfg = $this->module['config'];
		if (empty($token)){
			header('location:'.$cfg['outurl']);
			exit;
		}
		$m = get('select outtimetoken from ' . tablename('junsion_challeng_mem') . " where id = '{$mid}'");
		$t = unserialize($m['outtimetoken']);
		$w = $cfg['wechat'];
		if ($t['token'] != $token || time() - $t['time'] >= $cfg['outtime']){
			header('location:'.$cfg['outurl']);
			exit;
		}
		foreach ($w as $value) {
			if ($value['wechat'] == $t['wid']){
				header('location:'.$value['link']);
				exit;
			}
		}
		header('location:'.$cfg['outurl']);
		exit;
	}
	
	public function doMobileApi(){
		global $_W,$_GPC;
		$input = $_GPC['__input'];
		if ($input){
			if($input['Event']=='user_enter_tempsession'){
				$openid = $input['FromUserName'];
				if (empty($openid)) return '';
				$mem = pdo_fetch('select id,unionid from ' . tablename('junsion_challeng_mem') . " where propenid = '{$openid}'");
				$cfg = $this->module['config'];
				$wechat = $cfg['wechat'];
				$link = $this->getGuide($wechat, $mem, $cfg['outtime']>0);//获取未经关注的
				if(empty($link)) return ;
				if ($cfg['outtime'] > 0){
					$token = array('token'=>random(20),'time'=>time(),'wid'=>$link);
					update('mem',array('outtimetoken'=>serialize($token)),array('id'=>$mem['id']));
					$link = $_W['siteroot']."app".substr($this->createMobileUrl('url',array('mid'=>$mem['id'],'token'=>$token['token'])), 1);
				}
				$token = $this->getAccessToken();
				$post_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$token;
				load()->func('communication');
				$post_data = json_encode(array(
						'touser' =>$openid,
						'msgtype' => 'link',
						'link' => array(
								'title'=>$cfg['guide']['title'],
								'description'=>$cfg['guide']['des'],
								'url'=>$link,
								'thumb_url'=>toimage($cfg['guide']['logo']),
						),
				),JSON_UNESCAPED_UNICODE);
				$json = ihttp_post($post_url,$post_data);
				file_put_contents(IA_ROOT."/addons/junsion_challeng/msg", $post_data."\n".$json['content']."\n");
			}
		}else return $_GPC['echostr'];
	}
	
	private function getAccessToken() {
		global $_W;
		load()->model('wxapp');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->getAccessToken();
		return $token;
	}
	
}
